import React from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import { useTheme } from '../theme/ThemeContext';
import { Timer } from '../components/Timer';
import { createTimerRecord } from '../database/database';
import type { RootStackScreenProps } from '../navigation/types';

export const TimerScreen = () => {
  const route = useRoute<RootStackScreenProps<'Timer'>['route']>();
  const navigation = useNavigation();
  const { theme } = useTheme();
  const { planId } = route.params;

  const handleTimerStop = async (duration: number) => {
    try {
      const now = new Date();
      const startTime = new Date(now.getTime() - duration * 1000);
      
      await createTimerRecord({
        planId,
        startTime: startTime.toISOString(),
        endTime: now.toISOString(),
        duration,
      });

      Alert.alert('成功', '计时记录已保存', [
        {
          text: '确定',
          onPress: () => navigation.goBack(),
        },
      ]);
    } catch (error) {
      console.error('Error saving timer record:', error);
      Alert.alert('错误', '保存计时记录失败');
    }
  };

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.background }]}>
      <Timer onStop={handleTimerStop} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
}); 